package jmine.tec.json;

import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.Collections;

import org.apache.commons.lang.StringEscapeUtils;

/**
 * Representacao de String em JSON
 * 
 * @author takeshi
 */
public class JSONString extends AbstractJSONObject implements JSON {

    private final String string;

    /**
     * @param string String
     */
    public JSONString(String string) {
        super();
        this.string = string;
    }

    /**
     * {@inheritDoc}
     */
    public JSON getProperty(String propertyName) {
        return JSONNullObject.INSTANCE;
    }

    /**
     * {@inheritDoc}
     */
    public Collection<String> getPropertyNames() {
        return Collections.emptyList();
    }

    /**
     * {@inheritDoc}
     */
    public void setProperty(String propertyName, JSON value) {
    }

    /**
     * {@inheritDoc}
     */
    public String getString() {
        return this.string;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return this.string;
    }

    /**
     * {@inheritDoc}
     * 
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((this.string == null) ? 0 : this.string.hashCode());
        return result;
    }

    /**
     * {@inheritDoc}
     * 
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (this.getClass() != obj.getClass()) {
            return false;
        }
        JSONString other = (JSONString) obj;
        if (this.string == null) {
            if (other.string != null) {
                return false;
            }
        } else if (!this.string.equals(other.string)) {
            return false;
        }
        return true;
    }

    /**
     * {@inheritDoc}
     */
    public Writer write(Writer writer) throws IOException {
        writer.append('\"');
        writer.append(StringEscapeUtils.escapeJavaScript(this.string));
        writer.append('\"');
        return writer;
    }

}
